package com.itheima.dao;

import com.itheima.domian.Student;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class StudentDao {

    private static ArrayList<Student> studentList = new ArrayList<>(List.of(new Student(0,"张三","男",23),
            new Student(1,"李四","女",14)));
    private static final Logger LOGGER = LoggerFactory.getLogger(StudentDao.class);
    private static final File FILE = new File("Student_Server\\Student.txt");


    public ArrayList<Student> readFromFile() {

        try {
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream(FILE));
            studentList = (ArrayList<Student>) ois.readObject();
        } catch (IOException | ClassNotFoundException e) {
            LOGGER.warn("[服务器端]服务器端反序列化异常.");
        }
        return studentList;
    }

    public void writeTOFile() {
        try {
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(FILE));
            oos.writeObject(studentList);
        } catch (IOException e) {
            LOGGER.warn("[服务器端]服务器端序列化异常.");
        }

    }

    public void deleteStudent(Integer deleteId) {

        ArrayList<Student> students = readFromFile();
        Student student1 = null;
        for (Student student : students) {
            if (student.getId().equals(deleteId)){
                student1 = student;
            }
        }

        boolean remove = studentList.remove(student1);
        //测试用的
        System.out.println(remove);
        //序列化
        writeTOFile();
        LOGGER.info("[服务器]删除了id为"+deleteId+"的用户");
    }

    public void findAllStudent() {
    }

    public void updateStudent(int flag,Student student) {

        studentList = readFromFile();
        //根据StudentService传来的数据,修改指定索引的值为student
        studentList.set(flag,student);
        writeTOFile();
        LOGGER.info("[服务器]更新了数据!");
    }

    //没用
    public Student findStudent(int id) {

        ArrayList<Student> students = readFromFile();
        Student student = null;
        for (Student student1 : students) {
            if (student1.getId()==id){
                student = student1;
            }
        }
        return student;
    }

    public void addStudent(Student student) {
        writeTOFile();
        readFromFile();
        studentList.add(student);
        writeTOFile();
        LOGGER.info("[服务器端]服务器端已经将数据序列化进文件.");
    }
}
